package com.up.api.study.redission;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * @author: liuchengjun
 * @title: RedissonService
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2024/2/2/002 10:46 (星期五)
 * @since V2.0
 */
@Component
public class RedissonService {
    private Integer num = 2;
    private Integer num1 = 2;
    private final String LOCO_KEY = "TEST";
    @Resource
    private RedissonClient redissonClient;
    public void miaosha(){
        RLock lock = redissonClient.getLock(LOCO_KEY);
        lock.lock();
        //业务逻辑
        try {
            if(num1>0){
                System.out.println("获取商品"+num1);
                num1--;
            }else {
                System.out.println("商品已清空");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if(lock!=null)
            {
                lock.unlock();
            }
        }
    }
    public void miaosha1(){
        //业务逻辑
        try {
            if(num>0){
                System.out.println("获取商品"+num);
                num--;
            }else {
                System.out.println("商品已清空");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void test() {
        for (int i = 0; i < 10; i++) {
            CompletableFuture.runAsync(()->miaosha());
        }
    }


}
